#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# BSD License
# Copyright (c) 2011, Wang Qiang
# All rights reserved.

"""
Sending email through gmail.
"""

import smtplib
from email.mime.text import MIMEText

class GmailServer(object):
    """
    Class for sending email through gmail server.
    """
    def __init__(self, account, password):
        self.account = account
        self.password = password
        
    def setTo(self, receiver):
        self.receiver = receiver  

    def setFrom(self, sender):
        self.sender = sender

    def setSubject(self, subject):
        self.subject = subject

    def SendMsg(self, message):
        """
        Send email via gmail
        """
        mailserver = smtplib.SMTP("smtp.gmail.com")
        mailserver.ehlo()
        mailserver.starttls()
        mailserver.ehlo()
        username = self.account
        password = self.password
        mailserver.login(username, password)
        msg = MIMEText(message)
        msg['Subject'] = self.subject
        msg['From'] = self.sender
        msg['To'] = ','.join(self.receiver)
        mailserver.sendmail(self.sender, self.receiver,
                            msg.as_string())
        mailserver.quit()

    @staticmethod
    def SetupServer(account, password):
        return GmailServer(account, password)

    @staticmethod
    def SendEmail(server, sender, receiver, subject, msg):
        """
        Send Email via gmail.
        @param server: GmailServer instance
        @param sender: sender address
        @param receiver: receiver address list
        @param subject: email subject
        @param msg: email message
        """
        server.setFrom(sender)
        server.setTo(receiver)
        server.setSubject(subject)
        server.SendMsg(msg)


if __name__ == "__main__":
    server = GmailServer.SetupServer('wangqiang8511@gmail.com', 'wang8510')
    GmailServer.SendEmail(server, 'wangqiang8511@soy.com',
                          ['wang0586@e.ntu.edu.sg', 'wolfking222222@163.com'],
                          'Activation Email', 'Hello World!')
